package com.demo.phone.autohome;

import com.alibaba.fastjson.JSON;
import com.demo.phone.autohome.config.AutoHomeConfig;
import com.demo.phone.autohome.enums.ResultEnum;
import com.demo.phone.autohome.res.BaseResponse;
import com.demo.phone.autohome.res.leads.SyncLeadsAndGenTelResPonse;
import com.demo.phone.utils.HttpUtil;
import com.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author : YU.TAN
 * @date : 2021/10/29 14:30
 */
@Component
public class AutoHomeService {

    @Autowired
    private AutoHomeConfig autoHomeConfig;
    @Autowired
    private RedisUtil redisUtil;

    private static final String RESPONSE_TYPE = "token";

    private static final String AUTOHOME_TOKEN = "token";

    /**
     * 获取TOKEN并缓存
     */
    String getToken() {
        String token = null;
        Map<String, String> map = new HashMap<>(16);
        map.put("client_id", autoHomeConfig.getClientId());
        map.put("client_secret", autoHomeConfig.getClientSecret());
        map.put("response_type", RESPONSE_TYPE);

        String data = JSON.toJSONString(map);
        try {
            String result = HttpUtil.sendPost(data, autoHomeConfig.getAuthorizeUrl());
            TokenResult tokenResult = JSON.parseObject(result, TokenResult.class);
            token = tokenResult.getAccess_token();
            redisUtil.setKey(AUTOHOME_TOKEN, token, 7200, TimeUnit.SECONDS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 获取Header参数
     */

    String getAuthorization(Map<String, String> map) {
        String authorization = null;

        String cooperatorId = map.get("cooperatorId");
        String token = map.get("access_token");

        //加密
        authorization = "OEsyRk9rZzVlUWw2M2s4bThvTHJxS0c1UXZuYjBvTThxZk16UFdHaGxCQ29jM2l3aHRMN2pZenJxRFR0NXpLSQ==";
        return authorization;
    }

    public <T extends BaseResponse> T executeRequest(Object object, String url, T t) {
//        String token = (String) redisUtil.get(AUTOHOME_TOKEN);
//
//        if (StringUtils.isBlank(token)) {
//            token = getToken();
//            if (token == null) {
//                return null;
//            }
//        }

        Map<String, String> map = new HashMap<>(16);
        map.put("cooperatorId", autoHomeConfig.getCooperatorId());
//        map.put("access_token",token);
        String authorization = getAuthorization(map);

        //完善请求URl
        String requestUrl = url + "?cooperatorId=" + autoHomeConfig.getCooperatorId();


        Map<String, String> headerMap = new HashMap<>(16);
        headerMap.put("Authorization", authorization);


        try {
            List<Object> list = new ArrayList<>();
            list.add(object);
            String data = JSON.toJSONString(list);
            String result = HttpUtil.sendPost(data, headerMap, requestUrl);

            return JSON.parseObject(result, (Type) t.getClass());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public  boolean verifyResult(SyncLeadsAndGenTelResPonse baseRespond) {
        ResultEnum resultEnum = ResultEnum.getByCode(baseRespond.getReturncode());
        if (resultEnum == ResultEnum.SUCCESS) {
            return true;
        } else {
            return false;
        }
    }
}
